package com.fingard.dsp.bank.directbank.weixin01;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IOtherElse;
import com.fingard.dsp.bank.reqrespobj.otherelse.ReqOtherElse;
import com.fingard.dsp.bank.reqrespobj.otherelse.RetAtsOtherElse;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class WEIXIN01OtherElse extends WEIXIN01Base implements IOtherElse {
	public RetAtsOtherElse d_else(ReqOtherElse p_reqElse) throws Exception {
		if (p_reqElse.reqHeader.transType.equals("VerifySign")) {
			return verifySign(p_reqElse);
		} else if (p_reqElse.reqHeader.transType.equals("GetOpenID")) {
			return codeGetOpenId(p_reqElse);
		} else if ("GetUnionID".equals(p_reqElse.reqHeader.transType)) {
			return getUnionID(p_reqElse);
		} else {
			RetAtsOtherElse retAts = new RetAtsOtherElse(p_reqElse.reqHeader);
			retAts.retHashMap = new HashMap<String, String>();
			retAts.retHashMap.put("RespCode", "-1");
			retAts.retHashMap.put("RespInfo", "未知的TransType：" + p_reqElse.reqHeader.transType);
			return retAts;
		}
	}

	public RetAtsOtherElse codeGetOpenId(ReqOtherElse p_reqElse) {
		RetAtsOtherElse retAts = new RetAtsOtherElse(p_reqElse.reqHeader);
		retAts.retHashMap = new HashMap<String, String>();

		try {
			String ownAct = "";
			if (p_reqElse.reqHashMap.containsKey("OurBankAccount")) {
				ownAct = p_reqElse.reqHashMap.get("OurBankAccount");
			}

			String accessCode = "";
			if (p_reqElse.reqHashMap.containsKey("Code")) {
				accessCode = p_reqElse.reqHashMap.get("Code");
			}

			ActSetItem actItem = this.getBankConfig().getActSetItem(ownAct, "unifiedorder");
			if (actItem != null) {
				Map<String, String> hashMap = getOpenid(actItem.appId, actItem.appSecret, accessCode);
				
				String openId = hashMap.get("openid");
				if (StringHelper.hasAnyChar(openId)) {
					retAts.retHashMap.put("RespCode", "0");
					retAts.retHashMap.put("RespInfo", "成功");
					retAts.retHashMap.put("OpenId", openId);
				} else {
					retAts.retHashMap.put("RespCode", "-1");
					
					String tmpRespInfo = hashMap.get("RespInfo");
					if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
						tmpRespInfo = hashMap.get("errmsg");
					}
					retAts.retHashMap.put("RespInfo", tmpRespInfo);
				}
			} else {
				retAts.retHashMap.put("RespCode", "-1");
				retAts.retHashMap.put("RespInfo", "未找到账号[" + ownAct + "]商户配置信息!");
			}
		} catch (Exception ex) {
			ex.getMessage();
			retAts.retHashMap.put("RespCode", "-1");
			retAts.retHashMap.put("RespInfo", ex.getMessage());
			WriteBankLogLn(ex);
		}
		return retAts;
	}
	
	public RetAtsOtherElse getUnionID(ReqOtherElse p_reqElse) {
		RetAtsOtherElse retAts = new RetAtsOtherElse(p_reqElse.reqHeader);
		retAts.retHashMap = new HashMap<String, String>();

		try {
			String ownAct = "";
			if (p_reqElse.reqHashMap.containsKey("OurBankAccount")) {
				ownAct = p_reqElse.reqHashMap.get("OurBankAccount");
			}

			ActSetItem actItem = this.getBankConfig().getActSetItem(ownAct, "unifiedorder");
			if (actItem != null) {
				ArrayList<String> arrayParams = new ArrayList<String>();
				
				StringBuilder sbXml = new StringBuilder();
				sbXml.append("<xml>\r\n");
				
				sbXml.append("  <appid>" + actItem.appId + "</appid>\r\n");
				arrayParams.add("appid=" + actItem.appId);
				
				sbXml.append("  <mch_id>" + actItem.merchantId + "</mch_id>\r\n");
				arrayParams.add("mch_id=" + actItem.merchantId);
				
				sbXml.append("  <out_trade_no>" + p_reqElse.reqHashMap.get("RdSeq") + "</out_trade_no>\r\n");
				arrayParams.add("out_trade_no=" + p_reqElse.reqHashMap.get("RdSeq"));
				
				String nonce_str = get_nonce_str();
				sbXml.append("  <nonce_str>" + nonce_str + "</nonce_str>\r\n");
				arrayParams.add("nonce_str=" + nonce_str);
				
				sbXml.append("  <openid>" + p_reqElse.reqHashMap.get("Openid") + "</openid>\r\n");
				arrayParams.add("openid=" + p_reqElse.reqHashMap.get("Openid"));
				
				String[] signParams = new String[arrayParams.size()];
				arrayParams.toArray(signParams);
				
				String sign = signMessage(signParams, actItem.saltKey);
				sbXml.append("  <sign>" + sign + "</sign>\r\n");
				sbXml.append("</xml>");
				
				String[] tmpStrRet = sendToBank(sbXml.toString(), "getUnionID");
				
				if (tmpStrRet[0].length() == 0) {
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1],	tmpSbMsg);
					if (tmpBkReader != null) {
						String returnCode = tmpBkReader.getFirstText("/xml/return_code");
						if ("SUCCESS".equals(returnCode)) {
							String resultCode = tmpBkReader.getFirstText("/xml/result_code");
							if ("SUCCESS".equals(resultCode)) {
								retAts.retHashMap.put("RespCode", "0");
								retAts.retHashMap.put("RespInfo", tmpBkReader.getFirstText("/xml/return_msg"));
								retAts.retHashMap.put("Unionid", tmpBkReader.getFirstText("/xml/unionid"));
								retAts.retHashMap.put("Openid", tmpBkReader.getFirstText("/xml/openid"));
							} else {
								retAts.retHashMap.put("RespCode", "-1");
								retAts.retHashMap.put("RespInfo", tmpBkReader.getFirstText("/xml/err_code_des"));
							}
						} else {
							retAts.retHashMap.put("RespCode", "-1");
							retAts.retHashMap.put("RespInfo", tmpBkReader.getFirstText("/xml/return_msg"));
						}
					} else {
						retAts.retHashMap.put("RespCode", "-1");
						retAts.retHashMap.put("RespInfo", tmpSbMsg.toString());
					}
				} else {
					retAts.retHashMap.put("RespCode", "-1");
					retAts.retHashMap.put("RespInfo", tmpStrRet[1]);
				}
			} else {
				retAts.retHashMap.put("RespCode", "-1");
				retAts.retHashMap.put("RespInfo", "未找到账号[" + ownAct + "]商户配置信息!");
			}
		} catch (Exception ex) {
			ex.getMessage();
			retAts.retHashMap.put("RespCode", "-1");
			retAts.retHashMap.put("RespInfo", ex.getMessage());
			WriteBankLogLn(ex);
		}
		return retAts;
	}

	public RetAtsOtherElse verifySign(ReqOtherElse p_reqElse) {
		RetAtsOtherElse retAts = new RetAtsOtherElse(p_reqElse.reqHeader);
		retAts.retHashMap = new HashMap<String, String>();
		try {
			String ownAct = "";
			if (p_reqElse.reqHashMap.containsKey("OurBankAccount")) {
				ownAct = p_reqElse.reqHashMap.get("OurBankAccount");
			}
			String merchantId = "";
			if (p_reqElse.reqHashMap.containsKey("MchId")) {
				merchantId = p_reqElse.reqHashMap.get("MchId");
			}
			String appId = "";
			if (p_reqElse.reqHashMap.containsKey("AppId")) {
				appId = p_reqElse.reqHashMap.get("AppId");
			}

			String plain = "";
			if (p_reqElse.reqHashMap.containsKey("Plain")) {
				plain = p_reqElse.reqHashMap.get("Plain");
			} else {
				retAts.retHashMap.put("RespCode", "-1");
				retAts.retHashMap.put("RespInfo", "没有原文参数");
				return retAts;
			}

			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(ownAct, merchantId, appId, "unifiedorder");
			if (actItem != null) {
                String saltKey = actItem.saltKey;
                if (actItem.saltKeyMap != null) {
                    if ("APP01".equalsIgnoreCase(p_reqElse.reqHashMap.get("CommandCode"))) {
                        saltKey = actItem.saltKeyMap.get("APP");
                    } else if ("WXWAP01".equalsIgnoreCase(p_reqElse.reqHashMap.get("CommandCode"))) {
                        saltKey = actItem.saltKeyMap.get("H5");
                    } else if ("WXNATIVE01".equalsIgnoreCase(p_reqElse.reqHashMap.get("CommandCode"))) {
                        saltKey = actItem.saltKeyMap.get("QR");
                    } else if ("WXJSAPI01".equalsIgnoreCase(p_reqElse.reqHashMap.get("CommandCode"))) {
                        saltKey = actItem.saltKeyMap.get("JSAPI");
                    }
                }
                if (StringHelper.isNullOrEmpty(saltKey)) {
                    saltKey = actItem.saltKey;
                }
                WriteBankLogLn("当前saltKey:" + saltKey);

				StringBuilder tmpSb = new StringBuilder();
				if (verifySign(plain, saltKey, tmpSb)) {
					retAts.retHashMap.put("RespCode", "0");
					retAts.retHashMap.put("RespInfo", "验签通过");
				} else {
					retAts.retHashMap.put("RespCode", "-1");
					retAts.retHashMap.put("RespInfo", tmpSb.toString());
				}
			} else {
				retAts.retHashMap.put("RespCode", "-1");
				retAts.retHashMap.put("RespInfo", "未找到账号[" + ownAct + "]商户配置信息");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.retHashMap.put("RespCode", "-1");
			retAts.retHashMap.put("RespInfo", ex.getMessage());
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
